package com.yiguantong.police.ui.utils;



import java.io.UnsupportedEncodingException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author szg 密码加密
 */
public class EncryptUtil {


    public static final String IV_KEY_AUTO = "1234567890123456";
    public static final String KEY_AUTO = "1234567890123456";


   /**
     * AES加密方法
     *
     * @param iv   初始化向量，16位英文数字组合
     * @param key  密钥，32位英文数字组合
     * @param text 明文
     * @return 密文
     */
    public static byte[] EncryptAES(byte[] iv, byte[] key, byte[] text) {
        try {
            AlgorithmParameterSpec algorithmParameterSpec = new IvParameterSpec(iv);
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = null;
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, algorithmParameterSpec);

            return cipher.doFinal(text);
        } catch (Exception ex) {
            return null;
        }
    }


    /**
     * 用于自动登录手机号加密
     * 此次加密作用是消除非对称加密后的特殊字符(配合ios做到同步)
     *
     * @param plainText 传入加密字符串（该加密是非对称加密后的秘钥）
     * @return 最终返回16进制字符串
     */
    public static String EncryptAutoring(String plainText) {
        if (plainText == null)
            return "";
        byte[] cipherBytes = null;
        try {
            //加密
            cipherBytes = EncryptUtil.EncryptAES(IV_KEY_AUTO.getBytes("UTF-8"), KEY_AUTO.getBytes("UTF-8"),
                    plainText.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (null == cipherBytes) {
            return "";
        }
        //转换成16进制字符串
        String resultStr = parseByte2HexStr(cipherBytes);
        return resultStr;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     * @author CDY
     * @since 2015-6-8
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


}
